package cluster

import (
	"Alpaca/conf"
	"Alpaca/network"
	"math"
	"time"
)

var (
	server  *network.TcpServer
	clients []*network.TcpClient
)

type ClusterAgent struct {
	conn *network.TcpConn
}

func newAgent(conn *network.TcpConn) network.Agent {
	a := new(ClusterAgent)
	a.conn = conn
	return a
}

func (a *ClusterAgent) Run() {}

func (a *ClusterAgent) OnClose() {}

func Init() {
	if conf.ServerAddr != "" {
		server.Addr = conf.ServerAddr
		server.MaxConn = int(math.MaxInt32)
		server.WriteChanLen = conf.WriteChanLen
		server.MaxMsgLen = math.MaxUint32
		server.NewAgent = newAgent

		server.Start()
	}

	for _, addr := range conf.RemoteAddrs {
		client := new(network.TcpClient)
		client.Addr = addr
		client.ConnNum = 1
		client.ConnectInterval = 3 * time.Second
		client.WriteChanLen = conf.WriteChanLen
		client.MaxMsgLen = math.MaxUint32
		client.NewAgent = newAgent

		client.Start()
		clients = append(clients, client)
	}
}

func Close() {
	if server != nil {
		server.Close()
	}

	for _, client := range clients {
		client.Close()
	}
}
